package rs.pnv.bank.handler;

import java.security.Security;

import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import javax.xml.ws.LogicalMessage;
import javax.xml.ws.handler.LogicalHandler;
import javax.xml.ws.handler.LogicalMessageContext;
import javax.xml.ws.handler.MessageContext;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.w3c.dom.Document;
import org.w3c.dom.Node;

import rs.pnv.util.doc.DocumentUtil;
import rs.pnv.util.xmlsec.SignDocUtil;

public class SignatureHandler implements LogicalHandler<LogicalMessageContext> {
	
	
	static {
		Security.addProvider(new BouncyCastleProvider());
		org.apache.xml.security.Init.init();
	}
	
	@Override
	public boolean handleMessage(LogicalMessageContext context) {

		System.out.println("SignatureHandler.handleMessage()");
		
		Boolean isResponse = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
		//Source source = context.getMessage().getPayload();
		
		if (isResponse) {
			// ako je sve prošlo dobro, vrati true da pređeš na sledeći handler
			System.out.println("Potpisivanje...");
			LogicalMessage message = context.getMessage();
			Source source = message.getPayload();
			
			Source signSource = addSignature(source);
			context.getMessage().setPayload(signSource);
			
			return true;
		} else {
			System.out.println("validacija i skidanje potpisa...");

			// ako je sve prošlo dobro, vrati true da pređeš na sledeći handler
			return true;
		}

	}

	@Override
	public boolean handleFault(LogicalMessageContext context) {

		// ako vraća false, znači da NE treba da se pozove handleFault metoda od sledećeg handler-a.
		// dakle, vratiti true, ako POSTOJI greška.
		return true;
	}

	@Override
	public void close(MessageContext context) {
		// TODO Auto-generated method stub

	}
	
	public Source addSignature(Source source) {
		 
		 SignDocUtil signDocUtil = new SignDocUtil();
		 Document document = DocumentUtil.convertToDocument(source);
		 Document signDocument = signDocUtil.docSignature(document, "/security/BankA.jks", "BankA", "/security/BankA.cer");
		 DocumentUtil.printDocument(signDocument);
		 Source signSource = new  DOMSource(signDocument);
		 
		 return signSource;
	}


}
